﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.ComponentModel;
using System.Web.Configuration;

namespace BySoft.Web.Controls
{
    public class PagingControl : CompositeControl
    {
        static PagingControl()
        {
            EventClick = new object();
        }

        const String MAX_NAVIGATE_PAGE_COUNT_FIELD = "MaxNavigatePageCount";
        const Int32 DEFAULT_MAX_NAVIGATE_PAGE_COUNT = 11;
        const String PAGE_COUNT_FIELD = "PageCount";
        const Int32 DEFAULT_PAGE_COUNT = 10;
        const String CURRENT_INDEX_FIELD = "CurrentIndex";
        const Int32 DEFAULT_CURRENT_INDEX = 0;

        const string RECORD_COUNT_FIELD = "RecordCount";
        const string PAGE_SIZE_FIELD = "PageSize";
        const Int32 RECORD_COUNT = 0;
        const Int32 PAGE_SIZE = 10;
        const string PRE_ID1 = "PAGE_PRE_ID1";
        const string PRE_ID2 = "PAGE_PRE_ID2";
        const string NEXT_ID1 = "PAGE_NEXT_ID1";
        const string NEXT_ID2 = "PAGE_NEXT_ID2";
        const string TEXT_PRESS_BUTTON_ID = "TEXT_PRESS_BUTTON_ID";
        const string TEXT_ID = "TEXT_ID";
        const string Validator_ID = "vlidator_ID";

        const string BTN_ID = "BTN_GO";

        #region RecordCount

        /// <summary>
        /// 显示
        /// </summary>
        [DefaultValue(RECORD_COUNT)]
        public Int32 RecordCount
        {
            get
            {
                if (ViewState[RECORD_COUNT_FIELD] == null)
                {
                    return RECORD_COUNT;
                }

                return (Int32)ViewState[RECORD_COUNT_FIELD];
            }
            set
            {
                if (value >= 0)
                {
                    if (ViewState[RECORD_COUNT_FIELD]==null||(ViewState[RECORD_COUNT_FIELD] != null && (Int32)ViewState[RECORD_COUNT_FIELD] != value))
                    {
                        ViewState[RECORD_COUNT_FIELD] = value;
                        CalculatePageCount();
                        this.ChildControlsCreated = false;
                    }
                    //else
                    //{
                        ViewState[RECORD_COUNT_FIELD] = value;
                    //}
                }
            }
        }
        #endregion

        #region PageSize
        [DefaultValue(PAGE_SIZE)]
        public Int32 PageSize
        {
            get
            {
                if (ViewState[PAGE_SIZE_FIELD] == null)
                {
                    int result = PAGE_SIZE;

                    if (System.Web.Configuration.WebConfigurationManager.AppSettings["PageSize"] != null &&
                        System.Web.Configuration.WebConfigurationManager.AppSettings["PageSize"].ToString() != "")
                    {
                        try
                        {
                            //从web.config读取分页大小
                            result = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.AppSettings["PageSize"].ToString());
                        }
                        catch
                        {
                        }
                    }
                    return result;
                }

                return (Int32)ViewState[PAGE_SIZE_FIELD];
            }
            set
            {
                if (value > 0)
                {
                    if (ViewState[PAGE_SIZE_FIELD] != null && (Int32)ViewState[PAGE_SIZE_FIELD] != value)
                    {
                        ViewState[PAGE_SIZE_FIELD] = value;
                        CalculatePageCount();
                        this.ChildControlsCreated = false;
                    }
                    else
                    {
                        ViewState[PAGE_SIZE_FIELD] = value;
                    }
                }
            }
        }
        #endregion

        #region PageCount

        /// <summary>
        /// 总页数
        /// </summary>
        [DefaultValue(DEFAULT_PAGE_COUNT)]
        public Int32 PageCount
        {
            get
            {
                if (ViewState[PAGE_COUNT_FIELD] == null)
                {

                    return CalculatePageCount();
                }
                return (Int32)ViewState[PAGE_COUNT_FIELD];
            }
        }

        #endregion

        #region CurrentIndex

        /// <summary>
        /// 当前页码，从-1开始
        /// </summary>
        [DefaultValue(DEFAULT_CURRENT_INDEX)]
        public Int32 CurrentIndex
        {
            get
            {
                if (ViewState[CURRENT_INDEX_FIELD] == null)
                {
                    return DEFAULT_CURRENT_INDEX;
                }

                return (Int32)ViewState[CURRENT_INDEX_FIELD];
            }
            set
            {
                if (value > -1)
                {
                    int nIndex = value;
                    if (value >= PageCount)
                    {
                        nIndex = PageCount - 1;
                    }
                    if (ViewState[CURRENT_INDEX_FIELD] != null && (Int32)ViewState[CURRENT_INDEX_FIELD] != nIndex)
                    {
                        this.ChildControlsCreated = false;
                    }
                    ViewState[CURRENT_INDEX_FIELD] = nIndex;
                }
            }
        }

        #endregion

        #region MaxNavigatePageCount

        /// <summary>
        /// 最大显示页码数
        /// </summary>
        [DefaultValue(DEFAULT_MAX_NAVIGATE_PAGE_COUNT)]
        public Int32 MaxNavigatePageCount
        {
            get
            {
                if (ViewState[MAX_NAVIGATE_PAGE_COUNT_FIELD] == null)
                {
                    return DEFAULT_MAX_NAVIGATE_PAGE_COUNT;
                }

                return (Int32)ViewState[MAX_NAVIGATE_PAGE_COUNT_FIELD];
            }
            set
            {
                ViewState[MAX_NAVIGATE_PAGE_COUNT_FIELD] = value;
            }
        }

        #endregion

        public int PreIndex
        {

            get
            {
                if (this.CurrentIndex <= 0)
                {
                    return -1;
                }
                else
                {
                    return CurrentIndex - 1;
                }
            }
        }
        public int NextIndex
        {
            get
            {
                if (CurrentIndex >= PageCount - 1)
                {
                    return -1;
                }
                else
                {
                    return CurrentIndex + 1;
                }
            }
        }

        private List<System.Web.UI.Control> m_Controls = new List<System.Web.UI.Control>();

        private int CalculatePageCount()
        {
            if (PageSize > 0)
            {
                int intPageCount = Math.Max(1, (Int32)Math.Ceiling((double)this.RecordCount / (double)this.PageSize));
                ViewState[PAGE_COUNT_FIELD] = intPageCount;
                return intPageCount;
            }
            else
            {
                return 0;
            }
        }

        #region CreateChildControls

        protected override void CreateChildControls()
        {
            this.Controls.Clear();
            this.m_Controls.Clear();

            Int32 startPageIndex, endPageIndex;



            if (this.PageCount > this.MaxNavigatePageCount)
            {
                Int32 centerPageIndex = this.CurrentIndex;
                Int32 sidePageCount = (this.MaxNavigatePageCount - 3) / 2;

                if (centerPageIndex - sidePageCount <= 1)
                {
                    centerPageIndex = sidePageCount + 1;
                }
                else if (centerPageIndex + sidePageCount >= this.PageCount - 2)
                {
                    centerPageIndex = this.PageCount - 2 - sidePageCount;
                }

                startPageIndex = centerPageIndex - sidePageCount;
                endPageIndex = centerPageIndex + sidePageCount;
            }
            else
            {
                startPageIndex = 0;
                endPageIndex = this.PageCount - 1;
            }

            if (startPageIndex > 0)
            {
                this.CreateLinkButton(0);
            }

            for (int i = startPageIndex; i <= endPageIndex; i++)
            {
                this.CreateLinkButton(i);
            }

            if (endPageIndex < this.PageCount - 1)
            {
                this.CreateLinkButton(this.PageCount - 1);
            }

            CreatePreAndNextButton();
            PageIndexLinkButton linkText = new PageIndexLinkButton();
            linkText.Click += new EventHandler(linkButton_Click);
            linkText.ID = TEXT_PRESS_BUTTON_ID;
            this.Controls.Add(linkText);
            HtmlInputText txt = new HtmlInputText();
            txt.ID = TEXT_ID;
            this.Controls.Add(txt);


            //Add by alex
            HtmlInputButton btn = new HtmlInputButton();
            btn.ID = BTN_ID;
            this.Controls.Add(btn);
        }

        #region CreateLinkButton

        private void CreateLinkButton(Int32 pageIndex)
        {
            if (pageIndex != CurrentIndex)
            {
                PageIndexLinkButton linkButton = new PageIndexLinkButton();
                linkButton.Text = (pageIndex + 1).ToString();
                linkButton.PageIndex = pageIndex;
                this.Controls.Add(linkButton);
                linkButton.Click += new EventHandler(linkButton_Click);

                this.m_Controls.Add(linkButton);
            }
        }

        #endregion

        protected void CreatePreAndNextButton()
        {
            PageIndexLinkButton linkButtonPre1 = new PageIndexLinkButton();
          
            PageIndexLinkButton linkButtonNext1 = new PageIndexLinkButton();



          
            linkButtonPre1.ID = "PAGE_PRE_ID1";
            linkButtonNext1.ID = "PAGE_NEXT_ID1";
           

            linkButtonPre1.Text = "&lsaquo;&lsaquo;上一页";
            linkButtonNext1.Text = "下一页&rsaquo;&rsaquo;";
          
            this.Controls.Add(linkButtonPre1);
            this.Controls.Add(linkButtonNext1);
         
            if (PreIndex < 0)
            {
                linkButtonPre1.Enabled = false;
            }
            else
            {
                linkButtonPre1.PageIndex = PreIndex;
               
                linkButtonPre1.Click += new EventHandler(linkButton_Click);
                            
            }
            this.m_Controls.Add(linkButtonPre1);
           
            this.m_Controls.Add(linkButtonNext1);
          
            if (NextIndex < 0)
            {
                linkButtonNext1.Enabled = false;
           
            }
            else
            {
                linkButtonNext1.PageIndex = NextIndex;
            
                linkButtonNext1.Click += new EventHandler(linkButton_Click);
          
            }
        }

        #endregion

        #region Render

        protected override void Render(HtmlTextWriter writer)
        {
            AddAttributesToRender(writer);
            Int32 lastIndex = -1;


            PageIndexLinkButton linkPre1 = (PageIndexLinkButton)this.FindControl(PRE_ID1);
            writer.Write(@"<div class=""page-bottom"">");
            writer.Write(@"<span>");
            writer.Write("共&nbsp;" + RecordCount.ToString() + "&nbsp;行&nbsp;|</span>");
            linkPre1.RenderControl(writer);

          
            PageIndexLinkButton linkText = (PageIndexLinkButton)this.FindControl(TEXT_PRESS_BUTTON_ID);
            linkText.Style["display"] = "none";
            linkText.RenderControl(writer);

            HtmlInputText txtPage = (HtmlInputText)this.FindControl(TEXT_ID);


            foreach (System.Web.UI.Control control in this.Controls)
            {
                PageIndexLinkButton linkButton = control as PageIndexLinkButton;

                if (linkButton != null && linkButton.ID == null)
                {


                    if (linkButton.PageIndex != lastIndex + 1)
                    {
                        if (linkButton.PageIndex == this.CurrentIndex + 1)
                        {
                            writer.Write(@" <span class=""page-cur"">" + (this.CurrentIndex + 1) + "</span> ");
                        }
                        else
                        {
                            if (linkButton.PageIndex != this.CurrentIndex + 1)
                            {
                                if (lastIndex < CurrentIndex)
                                {
                                    writer.Write(@" <span class=""page-break"">...</span> ");
                                    //linkPre2.RenderControl(writer);
                                }
                                else
                                {
                                    //linkNext2.RenderControl(writer);
                                    writer.Write(@" <span class=""page-break"">...</span> ");
                                }
                            }
                        }

                    }
                    writer.Write(" ");
                    linkButton.RenderControl(writer);
                    lastIndex = linkButton.PageIndex;
                }

            }
            if (lastIndex != this.PageCount - 1)
            {
                writer.Write(@" <span class=""page-cur"">" + (this.CurrentIndex + 1) + "</span> ");
            }
            writer.Write(" ");
            PageIndexLinkButton linkNext1 = (PageIndexLinkButton)this.FindControl(NEXT_ID1);
            linkNext1.RenderControl(writer);
            writer.Write("<span>&nbsp;");
//            txtPage.Attributes["onkeypress"] = @"if(event.keyCode==13){
//               var Reg = /^[1-9][0-9]*$/;
//               var strPageIndex=document.getElementById('" + txtPage.ClientID + @"').value;
//  if(Reg.test(strPageIndex)) {
//      if (navigator.appVersion.match(/\bMSIE\b/)){
//        document.getElementById('" + linkText.ClientID + @"').click();
//      }
//     else
//     javascript:__doPostBack('" + linkText.UniqueID + @"','');}
//    return false;}";
            txtPage.Style["width"] = "30px";
            txtPage.RenderControl(writer);
            writer.Write("</span>");
            writer.Write("<span>&nbsp;");
            //Add by alex
            HtmlInputButton btnGo = (HtmlInputButton)this.FindControl(BTN_ID);
            btnGo.Attributes["onclick"] = @"var Reg = /^[1-9][0-9]*$/;
               var strPageIndex=document.getElementById('" + txtPage.ClientID + @"').value;
                if(Reg.test(strPageIndex))
                {
                    if (navigator.appVersion.match(/\bMSIE\b/))
                    {
                        document.getElementById('" + linkText.ClientID + @"').click();
                    }
                    else
                        javascript:__doPostBack('" + linkText.UniqueID + @"','');
                }
                return false;";
            btnGo.Value = "跳转";
            btnGo.RenderControl(writer);
            writer.Write("</span>");
           
            

            writer.Write("</div>");
        }

        #endregion

        #region Event PageIndexClick

        protected virtual void OnPageIndexClick(PageIndexClickEventArgs e)
        {
            this.ChildControlsCreated = false;
            this.CurrentIndex = e.PageIndex;

            EventHandler<PageIndexClickEventArgs> handler = (EventHandler<PageIndexClickEventArgs>)base.Events[EventClick];
            if (handler != null)
            {
                handler(this, e);
            }
        }

        void linkButton_Click(object sender, EventArgs e)
        {

            PageIndexLinkButton pageIndexLinkButton = (PageIndexLinkButton)sender;
            HtmlInputText txtPage = (HtmlInputText)this.FindControl(TEXT_ID);
            if (pageIndexLinkButton.ID == TEXT_PRESS_BUTTON_ID)
            {
                try
                {
                    int page = Convert.ToInt32(txtPage.Value);
                    if (page > PageCount)
                    {
                        page = PageCount - 1;
                    }
                    else
                    {
                        page = page - 1;
                    }
                    pageIndexLinkButton.PageIndex = page;
                    //this.CurrentIndex = page - 1;
                    this.RaisePostBackEvent(page);
                }
                catch
                {
                }
            }
            else
            {
                //this.CurrentIndex = pageIndexLinkButton.PageIndex;
                this.RaisePostBackEvent(pageIndexLinkButton.PageIndex);
            }
        }

        private static readonly object EventClick;

        public event EventHandler<PageIndexClickEventArgs> PageIndexClick
        {
            add
            {
                base.Events.AddHandler(EventClick, value);
            }
            remove
            {
                base.Events.RemoveHandler(EventClick, value);
            }
        }

        public void RaisePostBackEvent(Int32 pageIndex)
        {
            this.OnPageIndexClick(new PageIndexClickEventArgs(pageIndex));
        }

        #endregion
    }

    #region PageIndexClickEventArgs

    public class PageIndexClickEventArgs : EventArgs
    {
        public PageIndexClickEventArgs(Int32 pageIndex)
        {
            this.m_PageIndex = pageIndex;
        }

        private Int32 m_PageIndex;

        public Int32 PageIndex
        {
            get { return m_PageIndex; }
        }
    }

    #endregion

    internal class PageIndexLinkButton : LinkButton
    {
        const String PAGEINDEX_FILED = "PageIndex";

        public Int32 PageIndex
        {
            get
            {
                if (this.ViewState[PAGEINDEX_FILED] != null)
                {
                    return (Int32)this.ViewState[PAGEINDEX_FILED];
                }

                return 0;
            }
            set
            {
                this.ViewState[PAGEINDEX_FILED] = value;
            }

        }
    }

}
